package com.hydra.tool.object;

import com.hydra.tool.system.Sys;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * Created by ZhengGong on 15/3/12.
 * Description 用于生成类中的属性对应的String常量 和 mapper中的where
 */
public class PojoConstantsUtil {
    private static final String PREFIX = "public static final String ";

    public static void console(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        StringBuilder fieldConstantsSb = new StringBuilder();
        StringBuilder selectMapperWhereSb = new StringBuilder();
        selectMapperWhereSb.append(" <select id=\"selectListWithMap\" resultMap=\"BaseResultMap\" parameterType=\"java.util.Map\" >\n" + "                select\n" + "                <include refid=\"Base_Column_List\" />\n" + "                from ").append(upperCaseTo_(clazz.getSimpleName()).toLowerCase());
        selectMapperWhereSb.append("\n<where>\n");

        boolean isFirst = true;
        for (Field field : fields) {
            if (!Modifier.isStatic(field.getModifiers())) {
                fieldConstantsSb.append(buildField(field));
                selectMapperWhereSb.append(buildMapperWhere(field, isFirst));
            }
            isFirst = false;
        }

        selectMapperWhereSb.append("</where>\n" +
                "<if test=\"pageOrder!=null\">\n" +
                "order by #{pageOrder}\n" +
                "</if>\n" +
                "limit #{pageStart}, #{pageRows}\n" +
                "</select>");

        Sys.pl(fieldConstantsSb.toString());
        Sys.pl("\n***************************\n");
        Sys.pl(selectMapperWhereSb.toString());
    }

    private static String buildField(Field field) {
        return PREFIX + upperCaseTo_(field.getName()).toUpperCase() + " = " + '"' + field.getName() + "\";\n";
    }

    private static String buildMapperWhere(Field field, boolean isFirst) {
        String and = "";
        if (!isFirst) {
            and = "and";
        }
        String template = "<if test=\"%s!=null\">\n" +
                "%s %s = #{%s}\n" +
                "</if>\n";

        return String.format(template, field.getName(), and, field.getName(), field.getName());
    }

    public static String upperCaseTo_(String word) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!Character.isLowerCase(c) && i != 0) {
                sb.append("_");
            }
            sb.append(c);
        }
        return sb.toString();
    }
}
